package com.learn.metrics.type.healthCheck;

import cn.hutool.core.thread.ThreadUtil;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.health.HealthCheck;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.health.SharedHealthCheckRegistries;
import com.learn.metrics.type.healthCheck.check.AsyncRandomHealthCheck;
import com.learn.metrics.type.healthCheck.check.RandomHealthCheck;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author XuYang
 * @since 2025/2/19 10:18
 */
public class HealthCheckExample {
    static {
        // 全局共享 健康检查 注册表
        SharedHealthCheckRegistries.add("registry1", new HealthCheckRegistry());
    }

    public static void start() {
        doStart(0, new RandomHealthCheck());
    }

    public static void startAsync(Integer interval) {
        doStart(interval, AsyncRandomHealthCheck.of(new RandomHealthCheck()));
    }

    private static void doStart(Integer interval, HealthCheck healthCheck) {
        HealthCheckRegistry registry = SharedHealthCheckRegistries.getOrCreate("registry1");
        registry.register("postgres", healthCheck);
        final Map<String, HealthCheck.Result> results = registry.runHealthChecks();
        ThreadUtil.sleep(interval, TimeUnit.SECONDS);
        for (Map.Entry<String, HealthCheck.Result> entry : results.entrySet()) {
            if (entry.getValue().isHealthy()) {
                System.out.println(entry.getKey() + " is healthy");
            } else {
                System.err.println(entry.getKey() + " is UNHEALTHY: " + entry.getValue().getMessage());
                final Throwable e = entry.getValue().getError();
                if (e != null) {
                    e.printStackTrace();
                }
            }
        }
        registry.shutdown();
    }
}
